package othersmodel

import (
	"fmt"
	"iptv_server/v3/src/database"
	"iptv_server/v3/src/settings"
)

type OthersDetail struct {
	// gorm.Model
	ID uint `gorm:"primarykey" json:"-"`
	// id         uint `gorm:"primaryKey"`

	Name string `json:"vod_name,omitempty"`
	Pic  string `gorm:"type:varchar(2048)" json:"vod_pic,omitempty"`

	//"Cate" : "cover",  # cover是合集. folder 是一行一行的目录模式!!!
	// 不用 vod_tag 这个了!
	// IsFolder    string    `json:"cate,omitempty"` //重定向到这个cateID, categoryID

	Year        string `gorm:"type:varchar(20)" json:"vod_year,omitempty"`
	Remark      string `json:"vod_remarks,omitempty"`
	Area        string `json:"vod_area,omitempty"`
	Type        string `json:"type_name,omitempty"`
	Actors      string `json:"vod_actor,omitempty"`
	Director    string `json:"vod_director,omitempty"`
	Description string `json:"vod_content,omitempty"`
	// Plays          []Play `json:"list,omitempty"`

	//
	VodId    string `gorm:"-" json:"vod_id"` // == ID 或 SubId非空时 ==/others/SubId/ID
	FolderId uint   `gorm:"index" json:"-"`
	DetailId uint   `gorm:"index" json:"-"`
	// Plays []OthersPlay `json:"-"`
	Vod_play_url  string `gorm:"-" json:"vod_play_url,omitempty"`
	Vod_play_from string `gorm:"-" json:"vod_play_from,omitempty"` // not null
}



type DetailContent struct {
	List []OthersDetail `json:"list"`
}

func GetDetail(folderid, id uint) (ret *DetailContent, err error) {
	var d OthersDetail
	ret = &DetailContent{
		List: make([]OthersDetail, 0),
	}

	err = database.DB.Where("folder_id = ? AND detail_id = ?", folderid, id).First(&d).Error
	if err != nil {
		return
	}

	d.VodId = fmt.Sprintf("%s/detail/%d/%d", settings.UrlPath_TvOthers, d.FolderId, d.DetailId)
	plays, err := GetPlayList(folderid, id)
	if err != nil {
		return
	}
	d.Vod_play_from = plays.From
	d.Vod_play_url = plays.Vod_play_url
	fmt.Printf("d.VodId: %v\n", d.VodId)
	fmt.Printf("d.Vod_play_url: %v\n", d.Vod_play_url)
	ret.List = append(ret.List, d)
	return
}

func GetDetails(folderid uint, page, limit int) (details []OthersDetail, count int64) {
	offset := limit * (page - 1)

	// count := new(int64)
	err := database.DB.Model(new(OthersDetail)).Where("folder_id = ?", folderid).Count(&count).Error
	fmt.Printf("count: %v\n", count)

	// detail := new(OthersDetail)
	// err := database.DB.Model(detail).Where("site_id = ?", siteId).Count(count).Error
	if err != nil {
		count = 0
		return
	}

	err = database.DB.Where("folder_id = ?", folderid).Limit(limit).Offset(offset).Find(&details).Error
	if err != nil {
		return nil, 0
	}

	for i, d := range details {
		d.VodId = fmt.Sprintf("%s/detail/%d/%d", settings.UrlPath_TvOthers, d.FolderId, d.DetailId)
		details[i] = d
		fmt.Printf("d.Name: %v\n", d.Name)
	}
	return
}
